package com.qidian.server.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.sql.Timestamp;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.qidian.common.Constants;
import com.qidian.common.Globals;
import com.qidian.common.MessageStatus;
import com.qidian.common.beans.AccountBean;
import com.qidian.common.beans.LoggerRecordBean;
import com.qidian.common.beans.MessageBean;
import com.qidian.common.beans.RechargeCardBean;
import com.qidian.common.beans.UserBean;
import com.qidian.server.MServer;
import com.qidian.server.Status;
import com.qidian.util.PageList;
import com.qidian.util.UtilDateTime;

public class UserServlet extends HttpServlet
{

	/**
	 * 
	 */
	private static final long serialVersionUID = 575190150385637446L;
	private static final Logger logger = Logger.getLogger(UserServlet.class.getName()) ;
	private static final MServer mserver = MServer.getInstance();
	
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException 
	{
		Status status = Status.OK ;
		String actionType = request.getParameter(ServletConstants.arg_action_type) ;
		
		response.setCharacterEncoding("utf8") ;
//		System.out.println(request.getQueryString()) ;
		try
		{
			// 检查参数
			if (actionType == null)
			{
		        RequestDispatcher disp = request.getRequestDispatcher("modules/user/login.html") ;
		        disp.forward(request, response) ;
		        return ;
			}
			else if ("login".equalsIgnoreCase(actionType))
				status = login(request,response) ;
			else if ("getLoginDlg".equalsIgnoreCase(actionType))
				status = getLoginDlg(request,response) ;
			else if ("getRegUserDlg".equalsIgnoreCase(actionType))
				status = getRegUserDlg(request,response) ;
			else if ("logout".equalsIgnoreCase(actionType))
				status = logout(request,response) ;
			else if ("regUser".equalsIgnoreCase(actionType))
				status = regUser(request,response) ;	
			else if ("createUser".equalsIgnoreCase(actionType))
				status = createUser(request,response) ;	
			else if ("rechargeUser".equalsIgnoreCase(actionType))
				status = rechargeUser(request,response);		
			else if ("getUserSideBar".equalsIgnoreCase(actionType))
				status = getUserSideBar(request,response);
			else if ("createAccount".equalsIgnoreCase(actionType))
				status = createAccount(request,response);
			else if ("createAccountA".equalsIgnoreCase(actionType))
				status = createAccountA(request,response);
			else if ("createRechargeCard".equalsIgnoreCase(actionType))
				status = createRechargeCard(request,response);	
			else if ("querySingleAccount".equalsIgnoreCase(actionType))
				status = querySingleAccount(request,response) ;
			else if ("rechargeAccount".equalsIgnoreCase(actionType))
				status = rechargeAccount(request,response);		
			else if ("queryAccountPlugin".equalsIgnoreCase(actionType))
				status = querySingleAccountPlugin(request,response) ;
			else if ("mergeAccount".equalsIgnoreCase(actionType))
				status = mergeAccount(request,response) ;
			else if ("createAccountByRC".equalsIgnoreCase(actionType))
				status = createAccountByRC(request,response) ;
			else if ("queryUser".equalsIgnoreCase(actionType))
				status = queryUser(request,response) ;
			// 在此语句后的动作需要检查session变量
			else if(request.getSession().getAttribute(ServletConstants.s_attr_user) == null)
				status = getLoginDlg(request,response) ;
			else if ("recycleAccount".equalsIgnoreCase(actionType))
				status = recycleAccount(request,response) ;
			else if ("accountManager".equalsIgnoreCase(actionType))
				status = createRechargeCard(request,response);  
			else if ("getCreateAccountDlg".equalsIgnoreCase(actionType))
	    		status = getCreateAccountDlg(request,response);
			else if ("getAccountList".equalsIgnoreCase(actionType))
	    		status = getAccountList(request,response);   
			else if ("getQueryAccountDlg".equalsIgnoreCase(actionType))
				status = getQueryAccountDlg(request,response) ;
			else if ("queryAccount".equalsIgnoreCase(actionType))
				status = queryAccount(request,response) ;
			else if ("getCreateRechargeCardDlg".equalsIgnoreCase(actionType))
				status = getCreateRechargeCardDlg(request,response) ;
			else if ("getQueryRechargeCardDlg".equalsIgnoreCase(actionType))
				status = getQueryRechargeCardDlg(request,response) ;
			else if ("queryRechargeCard".equalsIgnoreCase(actionType))
				status = queryRechargeCard(request,response) ;
			else if ("recycleRechargeCard".equalsIgnoreCase(actionType))
				status = recycleRechargeCard(request,response) ;
			else if ("getRechargeUserDlg".equalsIgnoreCase(actionType))
				status = getRechargeUserDlg(request,response) ;
			else if ("getRechargeAccountDlg".equalsIgnoreCase(actionType))
				status = getRechargeAccountDlg(request,response) ;
			else if ("getUpdateUserDlg".equalsIgnoreCase(actionType))
				status = getUpdateUserDlg(request,response) ;
			else if ("updateUser".equalsIgnoreCase(actionType))
				status = updateUser(request,response) ;
			else if ("getQueryAnswerRecordDlg".equalsIgnoreCase(actionType))
				status = getQueryAnswerRecordDlg(request,response) ;
			else if ("queryAnswerRecord".equalsIgnoreCase(actionType))
				status = queryAnswerRecord(request,response) ;
			else if ("getMergeAccountDlg".equalsIgnoreCase(actionType))
				status = getMergeAccountDlg(request,response) ;
			else if ("getReturnPointDlg".equalsIgnoreCase(actionType))
				status = getReturnPointDlg(request,response) ;
			else if ("returnPoint2Point".equalsIgnoreCase(actionType))
				status = returnPoint2Point(request,response) ;
    		else if ("getLoggerDlg".equalsIgnoreCase(actionType))
    			status = getQueryLoggerDlg(request,response) ;
    		else if ("queryLogger".equalsIgnoreCase(actionType))
    			status = queryLogger(request,response) ;
    		else if ("getQueryReturnRecordDlg".equalsIgnoreCase(actionType))
    			status = getQueryReturnRecordDlg(request,response) ;
    		else if ("queryReturnRecord".equalsIgnoreCase(actionType))
    			status = queryReturnRecord(request,response) ;
    		else if ("freezeAccount".equalsIgnoreCase(actionType))
    			status = freezeAccount(request,response) ;
    		else if ("unfreezeAccount".equalsIgnoreCase(actionType))
    			status = unfreezeAccount(request,response) ;
    		else if ("getUpdateSingleAccountDlg".equalsIgnoreCase(actionType))
    			status = getUpdateSingleAccountDlg(request,response) ;
    		else if ("updateSingleAccount".equalsIgnoreCase(actionType))
    			status = updateSingleAccount(request,response) ;
			else
				status = Status.INVALID_VALUE ;
		}
		catch(Exception e)
		{
		    e.printStackTrace() ;
		    logger.error(e.getMessage()) ;
		    status = Status.OTHER_ERROR ;
		}
		if (status != Status.OK)
		{
		    response.getWriter().write(status.toString()) ;
		}
	}
	private Status queryReturnRecord(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String account = request.getParameter(ServletConstants.arg_account) ;
//		String filterRight = request.getParameter(ServletConstants.arg_filter_right);
		String strPageNo = request.getParameter(ServletConstants.arg_page_no) ;
		String strMsgId = request.getParameter(ServletConstants.arg_msg_id);
		String strMinSendTime = request.getParameter(ServletConstants.arg_min_send_time) ;
		String strMaxSendTime = request.getParameter(ServletConstants.arg_max_send_time) ;
		String strGameType = request.getParameter(ServletConstants.arg_game_type) ;
		String strIP = request.getParameter(ServletConstants.arg_ip);
		String strStatus = request.getParameter(ServletConstants.arg_status);
		
		UserBean user = (UserBean)request.getSession().getAttribute(ServletConstants.s_attr_user) ;
		if (user == null)
			return Status.INVALID_ARGUMENT ;
		
		if (account != null && account.length() > 0 && !AccountBean.isValidFormat(account))
			return Status.INVALID_VALUE ;
		
		
		int gameType = -1 ;
		long msgId = -1 ;
		long minSendTime = -1 ;
		long maxSendTime = -1 ;
		int pageNo = 1 ;
		int status = Integer.MIN_VALUE ;
		try
		{
			if (strPageNo != null && strPageNo.length() > 0)
				pageNo = Integer.parseInt(strPageNo) ;
			if (strGameType != null && strGameType.length() > 0)
				gameType = Integer.parseInt(strGameType) ;
			if (strMsgId != null && strMsgId.length() > 0)
				msgId = Long.parseLong(strMsgId) ;
			if (strMinSendTime != null && strMinSendTime.length() > 6)
				minSendTime = Long.parseLong(strMinSendTime) ;
			if (strMaxSendTime != null && strMaxSendTime.length() > 6)
				maxSendTime = Long.parseLong(strMaxSendTime);
			if (strStatus != null && strStatus.length() > 0)
				status = Integer.parseInt(strStatus);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return Status.INVALID_VALUE ;
		}
		
		PageList pageList = Globals.getAnswerRecordListForSuper(pageNo, msgId, 
				account, null, gameType, MessageStatus.ANSWERED.status, strIP, null, 
				minSendTime, maxSendTime,user.getUserId());
		if (pageList.getList() == null)
			return Status.OTHER_ERROR ;
		
		StringBuffer result = new StringBuffer(2048) ;

        
    	result.append("<table cellpadding=\"0\" cellspacing=\"0\">");
			result.append("<tr>");
				result.append("<td>题号</td>");
				result.append("<td>项目类型</td>");
				result.append("<td>发送时间/答题用时</td>");
				result.append("<td>IP</td>");
				result.append("<td>答案</td>");
				result.append("<td>状态</td>");
				result.append("<td class=action>子账号</td>");
//				result.append("<td class=action>查看</td>");
				result.append("<td class=action>扣点</td>");
			result.append("</tr>");
			MessageBean message ;
			Timestamp temp = new Timestamp(System.currentTimeMillis()) ;
		
			for(int i = 0 ; i < pageList.getList().size() ; i ++)
			{
				message = (MessageBean)pageList.getList().get(i) ; 
				result.append("<tr>");
	                result.append("<td>").append(message.getId()).append("</td>");
					result.append("<td>").append(message.getGameType()).append("</td>");
					temp.setTime(message.getReceiveTime()) ;
					result.append("<td>").append(String.format("%02d-%02d %02d:%02d:%02d", temp.getMonth()+1,temp.getDate(),temp.getHours(),temp.getMinutes(),temp.getSeconds())).append("/");
					if(message.getAnswerTime()>0)
						result.append((message.getAnswerTime()-message.getReceiveTime())/1000) ;
					else
						result.append("-</td>");
					
					result.append("<td>").append(message.getIp()).append("</td>");
					result.append("<td>").append(message.getAnswer()==null?"-":message.getAnswer()).append("</td>");
					result.append("<td>").append(message.getMessageStatus()).append("</td>");
					AccountBean accountBean = Globals.getAccountBuffer().get(message.getAccountId()) ;
					if (accountBean != null)
						result.append("<td class=action>").append("<a href=\"#\" class=\"view\" onclick=\"showDialog('")
						.append(accountBean.getAccount()).append("','子账号'); return false;\">")
						.append(message.getAccountId()).append("</a>")
						.append("</td>");
					else
						result.append("<td class=action>").append(message.getAccountId()).append("</td>");
					result.append("<td>").append(message.getUPoint()).append("</td>") ;
//					result.append("<td class=action>") ;
//					if (message.getContent() == null)
//						result.append("-") ;
//					else
//					{
//						String path = Globals.getUploadDirAbsolutePath()+message.getId() ;
//						File file = new File(path);
//						if(!file.exists())
//						{	
//							file.createNewFile() ;
//							FileOutputStream fos = new FileOutputStream(file);
//							fos.write(message.getContent()) ;
//							fos.close() ;
//						}
//						path = Globals.getUploadRelativePath()+message.getId();
//						result.append("<a href=\"#\" class=\"view\" onclick=\"onShowImage('").append(path)
//						.append("'); return false;\">原图</a>") ;
//					}
//					result.append("</td>");
	            result.append("</tr>");
			}
        result.append("</table>");
        result.append(pageList.getPageInfo().getHtmlByAction("onQueryReturnRecord(this);"));
        
		response.getWriter().write(result.toString()) ;

		return Status.OK;		
	}
	private Status queryLogger(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		String operation = request.getParameter(ServletConstants.arg_operation) ;
//		String operator = request.getParameter(ServletConstants.arg_operator) ;
		String operaA = request.getParameter(ServletConstants.arg_operat_A) ;
		String operaB = request.getParameter(ServletConstants.arg_operat_B) ;
		String strPageNo = request.getParameter(ServletConstants.arg_page_no) ;
		
		String strMinSendTime = request.getParameter(ServletConstants.arg_min_recharge_time) ;
		String strMaxSendTime = request.getParameter(ServletConstants.arg_max_recharge_time) ;
		
		long startTime = -1 ;
		long endTime = -1 ;
		

		if (operation == null || operaA == null || operaB == null 
				|| strPageNo == null || strMinSendTime == null || strMaxSendTime == null )
			return Status.INVALID_ARGUMENT ;
		
		int pageNo = 1 ;
		try
		{
			if (strPageNo != null && strPageNo.length() > 0)
				pageNo = Integer.parseInt(strPageNo) ;
			if (strMinSendTime != null && strMinSendTime.length() > 6)
				startTime = Long.parseLong(strMinSendTime) ;
			if (strMaxSendTime != null && strMaxSendTime.length() > 6)
				endTime = Long.parseLong(strMaxSendTime) ;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return Status.INVALID_VALUE ;
		}
		UserBean user = (UserBean)request.getSession().getAttribute(ServletConstants.s_attr_user) ;
		if (user == null)
			return Status.INVALID_VALUE ;
		
		PageList pageList = Globals.getLoggerList(startTime, endTime, operation, 
				operaA, operaB, null, String.valueOf(user.getUserId()), pageNo) ;
		if (pageList.getList() == null)
			return Status.OTHER_ERROR ;
		
		StringBuffer result = new StringBuffer(2048) ;

    	result.append("<table cellpadding=\"0\" cellspacing=\"0\">");
			result.append("<tr>");
				result.append("<td>充值时间</td>");
				result.append("<td>操作人</td>");
				result.append("<td>操作类型</td>");
				result.append("<td>参数A</td>");
				result.append("<td>参数B</td>");
				result.append("<td>备注</td>");
			result.append("</tr>");
			LoggerRecordBean loggerRecord = null;
			Timestamp temp = new Timestamp(System.currentTimeMillis()) ;
			for(int i = 0 ; i < pageList.getList().size() ; i ++)
			{
				
				loggerRecord = (LoggerRecordBean)pageList.getList().get(i) ; 
				temp.setTime(loggerRecord.getCurTime()) ;
				result.append("<tr>");
				result.append("<td>").append(String.format("%04d-%02d-%02d %02d:%02d", 1900+temp.getYear(),temp.getMonth()+1,temp.getDate(),temp.getHours(),temp.getMinutes())).append("</td>") ;
				result.append("<td>").append(loggerRecord.getOperator()).append("</td>") ;
				result.append("<td>").append(loggerRecord.getOperation()).append("</td>") ;
				result.append("<td>").append(loggerRecord.getOpera_A()).append("</td>") ;
				result.append("<td>").append(loggerRecord.getOpera_B()).append("</td>") ;
				result.append("<td>").append(loggerRecord.getOpera_C()).append("</td>") ;
	            result.append("</tr>");
			}
        result.append("</table>");
        result.append(pageList.getPageInfo().getHtmlByAction("onQueryLogger(this);"));

		response.getWriter().write(result.toString()) ;

		return Status.OK;		
	}
	/**
	 * 冻结子账号
	 * 
	 * */
	private Status freezeAccount(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		String account = request.getParameter(ServletConstants.arg_account) ;
		UserBean userBean = (UserBean)request.getSession().getAttribute(ServletConstants.s_attr_user) ;
		Status status = mserver.s_freezeAccount(userBean,account);
		if (status == Status.OK)
		{
			response.getWriter().write(status.statusCode.toString()) ;
		}
		return status;
	}
	/**
	 * 解冻子账号
	 * 
	 * */
	private Status unfreezeAccount(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		String account = request.getParameter(ServletConstants.arg_account) ;
		UserBean userBean = (UserBean)request.getSession().getAttribute(ServletConstants.s_attr_user) ; 
		Status status = mserver.s_unfreezeAccount(userBean,account);
		if (status == Status.OK)
		{
			response.getWriter().write(status.statusCode.toString()) ;
		}
		return status;
	}
	private Status getQueryReturnRecordDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException
	{
		StringBuffer result = new StringBuffer(2048) ;
        result.append("<form >");
        		result.append("<h3>查询条件</h3>");
        					result.append("<div nowrap>");
        					result.append("<p>");
        						result.append("<label>子账号：</label><input id=account type=text class=textLong maxlength=48 />");
        						result.append("<label>题号：</label><input id=msgId type=text class=textSmall ></input>") ;
        						result.append("<label>项目类型：</label><input id=gameType type=text class=textSmall ></input>") ;
        						result.append("<input type=submit class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\"  value=\"提交查询\" onclick=\"onQueryReturnRecord();return false;\"/>");
        					result.append("</p>");
        					result.append("<p>");
                            result.append("<label>发送时间：</label><input id=sendDate name=sendDate type=text class=textDate value=").append(new Date(System.currentTimeMillis())).append("></input>从&nbsp;&nbsp;") ;
                            result.append("<input id=minSendTime  type=text class=\"textSmall timepicker\" value=\"00:00:00\"></input>到&nbsp;&nbsp;") ;
                            result.append("<input id=maxSendTime  type=text class=\"textSmall timepicker\" value=\"23:59:59\"></input>") ;
//        					result.append("<label>状态：</label><select id=status class=textMedium>");
//                    			AdminServlet.getMessageStatuOptions(result) ;
//                    		result.append("</select>");
                        	result.append("<label>IP：</label><input id=ip type=text class=textMedium ></input>") ;
                    		result.append("</p>");	
                    		result.append("</div>");
        result.append("</form>") ;
	    
		response.getWriter().write(result.toString()) ;
		
		return Status.OK;
	}
	
	private Status getQueryLoggerDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		StringBuffer result = new StringBuffer(2048) ;
        result.append("<form class=jNice>");
        		result.append("<h3>查询条件</h3>");
        		result.append("<div nowrap>") ;
                        	result.append("<p>");
                        	result.append("<label>操作类型：</label>");
                        	result.append("<select id=operation>");
                        	AdminServlet.getOperationOptions(result) ;
                        	result.append("</select>");
                        	result.append("<label>&nbsp;&nbsp;&nbsp;&nbsp;充值时间：</label><input id=rechargeDate type=text class=textDate value=").append(new Date(System.currentTimeMillis())).append(" />") ;
                        	result.append("从&nbsp;&nbsp;<input id=minRechargeTime type=text class=textSmall value=00:00:00 />") ;
                        	result.append("到&nbsp;&nbsp;<input id=maxRechargeTime type=text class=textSmall value=23:59:59 />") ;
                        	result.append("</p>");
                        	result.append("<p>") ;
                        	result.append("<label>参数A：</label><input id=operaA type=text class=textLong maxlength=48/>");                     	
                        	result.append("<label>参数B：</label><input id=operaB type=text class=textLong maxlength=48/>");
                        	result.append("</p>");
                        	result.append("<p>") ;
//                        	result.append("<label>操作人：</label><input id=operator type=text class=textMedium maxlength=20/>");
                    		result.append("<input class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\" type=\"submit\" value=\"查询\" onclick=\"onQueryLogger();return false;\"/>");
                result.append("</p></div>") ;
        result.append("</form>") ;

		response.getWriter().write(result.toString()) ;
		return Status.OK;
	}	
	private Status queryUser(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		StringBuffer result = new StringBuffer(64) ;
		String userName = request.getParameter(ServletConstants.arg_user_name) ;
		String password = request.getParameter(ServletConstants.arg_password) ;
		Status status = mserver.p2s_queryUser(userName, password, result) ;
		if (status == Status.OK)
			response.getWriter().write(result.toString()) ;
		return status;
	}
	private Status createAccountA(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		Status status = Status.OK ;
		String userName = request.getParameter(ServletConstants.arg_user_name) ;
		String password = request.getParameter(ServletConstants.arg_password) ;
		String strPoint = request.getParameter(ServletConstants.arg_point);
		String strValidDate = request.getParameter(ServletConstants.arg_valid_date);
//		String strBatchSize = request.getParameter(ServletConstants.arg_batch_size) ;
		String account = request.getParameter(ServletConstants.arg_account) ;
		if (strPoint == null || userName == null ||
				strValidDate == null || password == null || account == null)
			return Status.INVALID_ARGUMENT;
		
		int point = Integer.parseInt(strPoint);
		long validTime = 0 ;
		// 如果包含-,表示日期形式
		if (strValidDate.indexOf('-') >= 0 )
		{
			if (strValidDate.indexOf(':') > 0)
				validTime = java.sql.Timestamp.valueOf(strValidDate).getTime() ;
			else
				validTime = java.sql.Timestamp.valueOf(strValidDate+" 23:59:59").getTime() ;
			if (validTime < System.currentTimeMillis())
				return Status.INVALID_VALUE ;
		}
		else// 只是一个数字，表示天数形式
		{
			validTime = Long.parseLong(strValidDate) ;
			if (validTime < Constants.min_day_validity ||
					validTime > Constants.max_day_validity)
				return Status.INVALID_VALUE ;
			// 天数 转换为 毫秒数
			validTime = validTime*Constants.millseconds_per_day;
		}
//		int batchSize = Integer.parseInt(strBatchSize) ;
		StringBuffer result = new StringBuffer(48);
		status = mserver.p2s_createAccountA(userName, password, validTime, account, point, result) ;
		
		if (status == Status.OK)
		{
			response.getWriter().write(result.toString()) ;
		}
		return status ;
	}
	//	private Status createAccountA(HttpServletRequest request,
//			HttpServletResponse response) {
//		// TODO Auto-generated method stub
//		return null;
//	}
	private Status queryAnswerRecord(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		String account = request.getParameter(ServletConstants.arg_account) ;
//		String filterRight = request.getParameter(ServletConstants.arg_filter_right);
		String strPageNo = request.getParameter(ServletConstants.arg_page_no) ;
		String strMsgId = request.getParameter(ServletConstants.arg_msg_id);
		String strMinSendTime = request.getParameter(ServletConstants.arg_min_send_time) ;
		String strMaxSendTime = request.getParameter(ServletConstants.arg_max_send_time) ;
		String strGameType = request.getParameter(ServletConstants.arg_game_type) ;
		String strIP = request.getParameter(ServletConstants.arg_ip);
		String strStatus = request.getParameter(ServletConstants.arg_status);
		
		UserBean user = (UserBean)request.getSession().getAttribute(ServletConstants.s_attr_user) ;
		if (user == null)
			return Status.INVALID_ARGUMENT ;
		
//		boolean filter = true;
//		if("false".equalsIgnoreCase(filterRight))
//			filter = false ;
		if (account != null && account.length() > 0 && !AccountBean.isValidFormat(account))
			return Status.INVALID_VALUE ;
		
		
		int gameType = -1 ;
		long msgId = -1 ;
		long minSendTime = -1 ;
		long maxSendTime = -1 ;
		int pageNo = 1 ;
		int status = Integer.MIN_VALUE ;
		try
		{
			if (strPageNo != null && strPageNo.length() > 0)
				pageNo = Integer.parseInt(strPageNo) ;
			if (strGameType != null && strGameType.length() > 0)
				gameType = Integer.parseInt(strGameType) ;
			if (strMsgId != null && strMsgId.length() > 0)
				msgId = Long.parseLong(strMsgId) ;
			if (strMinSendTime != null && strMinSendTime.length() > 6)
				minSendTime = Long.parseLong(strMinSendTime) ;
			if (strMaxSendTime != null && strMaxSendTime.length() > 6)
				maxSendTime = Long.parseLong(strMaxSendTime);
			if (strStatus != null && strStatus.length() > 0)
				status = Integer.parseInt(strStatus);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return Status.INVALID_VALUE ;
		}
		
		PageList pageList = Globals.getAnswerRecordListForSuper(pageNo, msgId, 
				account, null, gameType, status, strIP, user.getUserName(), minSendTime, maxSendTime,-1L);
		if (pageList.getList() == null)
			return Status.OTHER_ERROR ;
		
		StringBuffer result = new StringBuffer(2048) ;

        
    	result.append("<table cellpadding=\"0\" cellspacing=\"0\">");
			result.append("<tr>");
				result.append("<td>题号</td>");
				result.append("<td>项目类型</td>");
				result.append("<td>发送时间/答题用时</td>");
				result.append("<td>IP</td>");
				result.append("<td>答案</td>");
				result.append("<td>状态</td>");
				result.append("<td class=action>子账号</td>");
				result.append("<td class=action>查看</td>");
			result.append("</tr>");
			MessageBean message ;
			Timestamp temp = new Timestamp(System.currentTimeMillis()) ;
		
			for(int i = 0 ; i < pageList.getList().size() ; i ++)
			{
				message = (MessageBean)pageList.getList().get(i) ; 
				result.append("<tr>");
	                result.append("<td>").append(message.getId()).append("</td>");
					result.append("<td>").append(message.getGameType()).append("</td>");
					temp.setTime(message.getReceiveTime()) ;
					result.append("<td>").append(String.format("%02d-%02d %02d:%02d:%02d", temp.getMonth()+1,temp.getDate(),temp.getHours(),temp.getMinutes(),temp.getSeconds())).append("/");
					if(message.getAnswerTime()>0)
						result.append((message.getAnswerTime()-message.getReceiveTime())/1000) ;
					else
						result.append("-</td>");
					
					result.append("<td>").append(message.getIp()).append("</td>");
					result.append("<td>").append(message.getAnswer()==null?"-":message.getAnswer()).append("</td>");
					result.append("<td>").append(message.getMessageStatus()).append("</td>");
					AccountBean accountBean = Globals.getAccountBuffer().get(message.getAccountId()) ;
					if (accountBean != null)
						result.append("<td class=action>").append("<a href=\"#\" class=\"view\" onclick=\"showDialog('")
						.append(accountBean.getAccount()).append("','子账号'); return false;\">")
						.append(message.getAccountId()).append("</a>")
						.append("</td>");
					else
						result.append("<td class=action>").append(message.getAccountId()).append("</td>");
					result.append("<td class=action>") ;
					if (message.getContent() == null)
						result.append("-") ;
					else
					{
						String path = Globals.getUploadDirAbsolutePath()+message.getId() ;
						File file = new File(path);
						if(!file.exists())
						{	
							file.createNewFile() ;
							FileOutputStream fos = new FileOutputStream(file);
							fos.write(message.getContent()) ;
							fos.close() ;
						}
						path = Globals.getUploadRelativePath()+message.getId();
						result.append("<a href=\"#\" class=\"view\" onclick=\"onShowImage('").append(path)
						.append("'); return false;\">原图</a>") ;
					}
					result.append("</td>");
	            result.append("</tr>");
			}
        result.append("</table>");
        result.append(pageList.getPageInfo().getHtmlByAction("onUserQueryAnswerRecord(this);"));
        
    	response.setCharacterEncoding("utf8") ;
		response.getWriter().write(result.toString()) ;

		return Status.OK;		
	}
	private Status getQueryAnswerRecordDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		StringBuffer result = new StringBuffer(2048) ;
        result.append("<form >");
        		result.append("<h3>查询条件</h3>");
        					result.append("<div nowrap>");
        					result.append("<p>");
        						result.append("<label>子账号：</label><input id=account type=text class=textLong maxlength=48 />");
        						result.append("<label>题号：</label><input id=msgId type=text class=textSmall ></input>") ;
        						result.append("<label>项目类型：</label><input id=gameType type=text class=textSmall ></input>") ;
        						result.append("<input type=submit class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\"  value=\"提交查询\" onclick=\"onUserQueryAnswerRecord();return false;\"/>");
        					result.append("</p>");
        					result.append("<p>");
                            result.append("<label>发送时间：</label><input id=sendDate name=sendDate type=text class=\"textDate datepicker\" onClick=\"this.datepicker();\" value=").append(new Date(System.currentTimeMillis())).append("></input>从&nbsp;&nbsp;") ;
                            result.append("<input id=minSendTime  type=text class=\"textSmall timepicker\" value=\"00:00:00\"></input>到&nbsp;&nbsp;") ;
                            result.append("<input id=maxSendTime  type=text class=\"textSmall timepicker\" value=\"23:59:59\"></input>") ;
        					result.append("<label>状态：</label><select id=status class=textMedium>");
                    			AdminServlet.getMessageStatuOptions(result) ;
                    		result.append("</select>");
                        	result.append("<label>IP：</label><input id=ip type=text class=textMedium ></input>") ;
                    		result.append("</p>");	
                    		result.append("</div>");
        result.append("</form>") ;
	    
		response.getWriter().write(result.toString()) ;
		
		return Status.OK;
	}
	private Status createAccountByRC(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		String userName = request.getParameter(ServletConstants.arg_user_name) ;
		String rechargeCard = request.getParameter(ServletConstants.arg_recharge_card) ;
		if(userName == null || rechargeCard == null)
			return Status.INVALID_ARGUMENT ;
		StringBuffer result = new StringBuffer(36) ;
		Status status = mserver.p2s_createAccountByRechargeCard(userName,rechargeCard,result) ;
		if(status == Status.OK)
			response.getWriter().write(result.toString()) ;
		return status;
	}
	private Status mergeAccount(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		String accountA = request.getParameter(ServletConstants.arg_account_a) ;
		String accountB = request.getParameter(ServletConstants.arg_account_b) ;
		
		if (accountA == null || accountB == null)
			return Status.INVALID_ARGUMENT ;
		
		StringBuffer result = new StringBuffer(36) ;
		Status status = mserver.p2s_mergeAccount(accountA,accountB,result) ;
		if (status.isOK())
			response.getWriter().write(result.toString()) ;
		return status;
	}
	private Status querySingleAccountPlugin(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		String account = request.getParameter(ServletConstants.arg_account) ;
		String username = request.getParameter(ServletConstants.arg_user_name) ;
		StringBuffer result = new StringBuffer(64) ;

		Status status = mserver.p2s_queryAccount(username,account, result) ;
		if(status.isOK())
		{
			response.getWriter().write(result.toString()) ;
		}
		return status;
	}
	private Status updateUser(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		Status status = Status.OK ;
		String userName = request.getParameter(ServletConstants.arg_user_name);
		String password  = request.getParameter(ServletConstants.arg_password);
		String newPassword = request.getParameter(ServletConstants.arg_new_password) ;
		String qq = request.getParameter(ServletConstants.arg_qq) ;
		String email = request.getParameter(ServletConstants.arg_email) ;
		String zhifubao = request.getParameter(ServletConstants.arg_zhifubao) ;
		String phone = request.getParameter(ServletConstants.arg_phone) ;

		if (userName == null || password == null || newPassword == null ||
				qq == null || email == null || zhifubao == null || phone == null)
			return Status.INVALID_ARGUMENT ;
		
		UserBean user = (UserBean)request.getSession().getAttribute(ServletConstants.s_attr_user);
		if(user == null || !user.getUserName().equalsIgnoreCase(userName))
			return Status.INVALID_VALUE ;
		if(!user.getPassword().equalsIgnoreCase(password))
			return Status.INVALID_USERNAME_OR_PASSWORD ;

		status =  mserver.s_updateUser(userName, password,newPassword ,qq, email,
				zhifubao,phone) ;
		if (status == Status.OK)
		{
			response.getWriter().write(Status.OK.toString()) ;
		}
		return status ;
	}
	private Status getUpdateUserDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		StringBuffer result = new StringBuffer(2048) ;
		UserBean user = (UserBean)request.getSession().getAttribute(ServletConstants.s_attr_user) ;
		result.append("<form>");
//      	result.append("<input type=hidden id=actionType name=actionType value=updateUser></input>");
       	result.append("<h3>开发者信息</h3>");
      	result.append("<fieldset>");
      		result.append("<p><label>用户名:</label><input disabled=disabled type=\"text\" name=\"userName\" id=\"userName\" class=\"text-medium\" maxlength=20 value=").append(user.getUserName()).append(" /></input></p>");
      		result.append("<p id=pOldPwd class=pUpdate><label>旧密码:</label><input type=\"password\" name=\"password\" id=\"password\" class=\"text-medium\" maxlength=20 ").append(" /></input></p>");
      		result.append("<p id=pPoint class=pShow><label>总点数:</label><input type=text name=\"password\" id=\"password\" class=\"text-medium\" maxlength=20 value=").append(user.getPoint()).append(" /></input></p>");
      		result.append("<p id=pUsedPoint class=pShow><label>已用点数:</label><input type=text class=\"text-medium\" maxlength=20 value=").append(user.getUsedPoint()).append(" /></input></p>");
      		result.append("<p id=pLeftPoint class=\"pShow\"><label>可用点数:</label><input type=text class=\"text-medium\" maxlength=20 value=").append(user.getLeftPoint()).append(" /></input></p>");
      		result.append("<p id=pReturnPoint class=pShow><label>返点:</label><input type=text class=\"text-medium\" maxlength=20 value=").append(String.format("%.2f",user.getReturnPoint())).append(" /></input></p>");
      		result.append("<p id=pReturnRatio class=pShow><label>返点比率:</label><input type=text class=\"text-medium\" maxlength=20 value=\"").append(String.format("%.2f",user.getReturnRatio()*100.0)).append("%\" /></input></p>");
      		result.append("<p id=pNewPwd class=\"pUpdate\"><label>新密码:</label><input type=\"password\" name=\"newPassword\" id=\"newPassword\" class=\"text-medium\" maxlength=20 /></input></p>");
      		result.append("<p id=pNewPwdCfm class=\"pUpdate\"><label>新密码确认:</label><input type=\"password\" name=\"newPasswordConfirm\" id=\"newPasswordConfirm\" class=\"text-medium\" maxlength=20 /></input></p>");
      		result.append("<p><label>QQ:</label><input type=\"text\" name=\"qq\" id=\"qq\" class=\"text-medium\" maxlength=12 value=\"").append(user.getQQ()).append("\" /></input></p>");
      		result.append("<p><label>Email:</label><input type=\"text\" name=\"email\" id=\"email\" class=\"text-medium\" maxlength=32 value=\"").append(user.getEmail()).append("\" /></input></p>");
      		result.append("<p><label>支付宝(邮箱或手机号):</label><input type=\"text\" name=zhifubao id=zhifubao class=\"text-medium\" maxlength=32 value=\"").append(user.getZhifubao()==null?"":user.getZhifubao()).append("\" /></input></p>");
      		result.append("<p><label>手机:</label><input type=\"text\" name=phone id=phone class=\"text-medium\" maxlength=12 value=\"").append(user.getPhone()==null?"":user.getPhone()).append("\" /></input></p>");
      		result.append("<p><input type=\"button\" class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\"  name=\"btnUpdateUser\" id=\"btnUpdateUser\" value=\"修改密码&资料\" onclick=\"onUpdateUser();\"/>").
            	append("<input type=\"button\"  class=\"x-hidden ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\" name=\"btnUpdateUser1\" id=\"btnUpdateUser1\" value=\"确认修改\" onclick=\"updateUser();\"/></p>");
      	result.append("</fieldset>");
      	result.append("</form>");

//		result.append("[{\"userName\":").append(user.getUserName())
//				.append(",\"point\":").append(user.getPoint())
//				.append(",\"usedPoint\":").append(user.getUsedPoint())
//				.append(",\"password\":").append(user.getPassword())
//				.append(",\"qq\":").append(user.getQQ())
//				.append(",\"email\":").append(user.getEmail())
//				.append("}]");

		response.getWriter().write(result.toString()) ;

        
        return Status.OK ;		
	}
	private Status getRegUserDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		StringBuffer result = new StringBuffer(2048);
		result.append("<form action=\"user\" method=\"GET\" name=\"regUserForm\" id=\"regUserForm\">");
      	result.append("<input type=hidden id=actionType name=actionType value=regUser></input>");
       	result.append("<h3>注册</h3>");
      	result.append("<fieldset>");
      		result.append("<p>用户名(数字、字母、下划线组成的6-20位的字符串):</p><p><input type=\"text\" name=\"userName\" id=\"userName\" class=\"text-medium\" maxlength=20/></input></p>");
      		result.append("<p>密码(数字、字母、下划线组成的6-20位的字符串):</p><p><input type=\"password\" name=\"password\" id=\"password\" class=\"text-medium\" maxlength=20/></input></p>");
      		result.append("<p>确认密码:</p><p><input type=\"password\" name=\"password_confirm\" id=\"password_confirm\" class=\"text-medium\" maxlength=20/></input></p>");
      		result.append("<p>QQ(用于技术支持等服务):</p><p><input type=\"text\" name=\"qq\" id=\"qq\" class=\"text-medium\" maxlength=12/></input></p>");
      		result.append("<p>Email(用于通知等服务):</p><p><input type=\"text\" name=\"email\" id=\"email\" class=\"text-medium\" maxlength=32/></input></p>");
            result.append("<p>验证码:</p><p><input type=\"text\" name=\"validCodeAnswer\" class=\"text-small\" id=\"validCodeAnswer\" value='' maxlength=4></input><img src=\"validatecode\" name=\"validImg\" id=\"validImg\"/><a href=\"javascript:show(document.getElementById('validImg'))\">看不清?</a></p>");
            result.append("<p><input type=\"submit\" class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\"  name=\"submit\" id=\"submit\" value=\"注册\" onClick=\"newUser();return false;\"/></p>");
      	result.append("</fieldset>");
      	result.append("</form>");
        

		response.getWriter().write(result.toString()) ;

        
        return Status.OK ;
	}
	private Status getLoginDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		
		StringBuffer result = new StringBuffer(2048);
		result.append("<form action=\"user\" method=\"GET\" name=\"loginForm\" id=\"loginForm\">");
       		result.append("<input type=hidden id=actionType name=actionType value=login></input>");
        	result.append("<h3>开发者登录</h3>");
       		result.append("<fieldset>");
       			result.append("<p>用户名:</p><p><input type=\"text\" name=\"userName\" id=\"userName\" class=\"text-medium\" maxlength=20/></input></p>");
       			result.append("<p>密码:</p><p><input type=\"password\" name=\"password\" id=\"password\" class=\"text-medium\" maxlength=20/></input></p>");
	            result.append("<p>验证码:</p><p><input type=\"text\" name=\"validCodeAnswer\" class=\"text-small\" id=\"validCodeAnswer\" value='' maxlength=4></input><img src=\"validatecode\" name=\"validImg\" id=\"validImg\"/><a href=\"javascript:show(document.getElementById('validImg'))\">看不清?</a></p>");
	            result.append("<p><input type=\"submit\" class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\"  name=\"submit\" id=\"submit\" value=\"登陆\" onclick=\"userLogin(); return false;\"/><input type=\"button\" class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\"  name=\"reg\" id=\"reg\" value=\"注册\" onClick=\"regUser(); return false;\"/></p>");
       		result.append("</fieldset>");
        result.append("</form>");
        
        
		response.getWriter().write(result.toString()) ;

        return Status.OK ;
	  	        
	}
	private Status rechargeAccount(HttpServletRequest request,
			HttpServletResponse response) 
	{
		Status status = Status.OK ;
		String account = request.getParameter(ServletConstants.arg_account) ;
		String rechargeCard = request.getParameter(ServletConstants.arg_recharge_card);
		if (rechargeCard == null || account == null)
			return Status.INVALID_ARGUMENT;
		
		StringBuffer result = new StringBuffer(10);
		status = mserver.p2s_rechargeAccount(account, rechargeCard, result) ;
		if (status == Status.OK)
		{
			try 
			{
				// 返回充值点数
				response.getWriter().write(result.toString()) ;
			}catch (IOException e){
				e.printStackTrace();
				status = Status.OTHER_ERROR ;
			}
		}
		return status ;
	}
	private Status getRechargeAccountDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		StringBuffer result = new StringBuffer(2048) ;
        result.append("<form action=\"user?actionType=rechargeAccount\" class=\"jNice\">");
        		result.append("<h3>子账号充值</h3>");
        		result.append("<fieldset>");
                        	result.append("<p><label>子账号:</label><input id=account type=\"text\" class=\"text-long\" maxlength=48/></p>");
                        	result.append("<p><label>充值卡号:</label><input id=rechargeCard type=\"text\" class=\"text-long\" maxlength=48/></p>");
                    		result.append("<input type=\"submit\" class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\"  value=\"充值\" onclick=\"rechargeAccount();return false;\"/>");
               result.append("</fieldset>");
        result.append("</form>") ;
	    
		response.getWriter().write(result.toString()) ;

		return Status.OK;
	}
	private Status getMergeAccountDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		StringBuffer result = new StringBuffer(2048) ;
        result.append("<form class=\"jNice\">");
        		result.append("<h3>子账号充值(新购的子账号的点数将合并到原有子账号)</h3>");
        		result.append("<fieldset>");
                        	result.append("<p><label>原有子账号:</label><input id=accountA type=\"text\" class=\"text-long\" maxlength=48/></p>");
                        	result.append("<p><label>新购的子账号:</label><input id=accountB type=\"text\" class=\"text-long\" maxlength=48/></p>");
                    		result.append("<input type=\"submit\" class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\"  value=\"充值\" onclick=\"mergeAccount();return false;\"/>");
               result.append("</fieldset>");
        result.append("</form>") ;
	    
		response.getWriter().write(result.toString()) ;

		return Status.OK;
	}	
	private Status getRechargeUserDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		UserBean user = (UserBean)request.getSession().getAttribute(ServletConstants.s_attr_user);
		StringBuffer result = new StringBuffer(2048) ;
        result.append("<form action=\"user?actionType=rechargeUser\" class=\"jNice\">");
        		result.append("<h3>开发者充值</h3>");
        		result.append("<fieldset>");
                        	result.append("<p><label>开发者用户名:</label><input id=userName type=\"text\" class=\"text-long\" maxlength=20 value=\"").append(user.getUserName()).append("\"/></p>");
                        	result.append("<p><label>充值卡号(此处只能使用平台提供的充值卡):</label><input id=rechargeCard type=\"text\" class=\"text-long\" maxlength=48/></p>");
                    		result.append("<input type=\"submit\" class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\"  value=\"充值\" onclick=\"rechargeUser();return false;\"/>");
               result.append("</fieldset>");
        result.append("</form>") ;
	    
		response.getWriter().write(result.toString()) ;

		return Status.OK;
	}
	private Status queryRechargeCard(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String rechargeCard = request.getParameter(ServletConstants.arg_recharge_card) ;
		String strMinValidDate = request.getParameter(ServletConstants.arg_min_valid_date);
		String strMaxValidDate = request.getParameter(ServletConstants.arg_max_valid_date);
		String strMinLeftPoint = request.getParameter(ServletConstants.arg_min_point) ;
		String strMaxLeftPoint = request.getParameter(ServletConstants.arg_max_point) ;
		String strPageNo = request.getParameter(ServletConstants.arg_page_no) ;
		
		if (rechargeCard != null && rechargeCard.length() > 0 && !AccountBean.isValidFormat(rechargeCard))
			return Status.INVALID_VALUE ;
		
		long minValidTime = 0 ;
		long maxValidTime = 0 ;
		int minLeftPoint = 0 ;
		int maxLeftPoint = 0 ;
		int pageNo = 1 ;
		try
		{
			if (strMinValidDate != null && strMinValidDate.length() == 10)
				minValidTime = java.sql.Timestamp.valueOf(strMinValidDate+" 00:00:00").getTime() ;
			if (strMaxValidDate != null && strMaxValidDate.length() == 10)
				maxValidTime = java.sql.Timestamp.valueOf(strMaxValidDate+" 23:59:59").getTime() ;
			if (strMinLeftPoint != null && strMinLeftPoint.length() > 0)
				minLeftPoint = Integer.parseInt(strMinLeftPoint) ;
			if (strMaxLeftPoint != null && strMaxLeftPoint.length() > 0)
				maxLeftPoint = Integer.parseInt(strMaxLeftPoint) ;
			if (strPageNo != null && strPageNo.length() > 0)
				pageNo = Integer.parseInt(strPageNo) ;
		}
		catch(Exception e)
		{
			return Status.INVALID_VALUE ;
		}
		
		UserBean user = (UserBean) request.getSession().getAttribute(ServletConstants.s_attr_user) ;
		if (user == null)
			return Status.INVALID_ARGUMENT ;
//		PageList pageList = Globals.getAccountList(user.getUserId(), pageNo, account, minValidTime, maxValidTime, minLeftPoint, maxLeftPoint);
		PageList pageList = Globals.getRechargeCardList(user.getUserId(),pageNo,rechargeCard,minValidTime,maxValidTime,minLeftPoint,maxLeftPoint) ;
		if (pageList.getList() == null)
			return Status.OTHER_ERROR ;
		
		StringBuffer result = new StringBuffer(2048) ;
		result.append("<h3>充值卡列表</h3>");
        result.append(pageList.getPageInfo().getHtmlByAction("onQueryRechargeCard(this);"));
    	result.append("<table cellpadding=\"0\" cellspacing=\"0\">");
			result.append("<tr>");
				result.append("<td>充值卡号</td>");
				result.append("<td>生成日期</td>");
				result.append("<td>有效期</td>");
				result.append("<td>点数</td>");
				result.append("<td class=\"action\">操作</td>");
			result.append("</tr>");
			RechargeCardBean rechargeCardBean ;
			for(int i = 0 ; i < pageList.getList().size() ; i ++)
			{
				rechargeCardBean = (RechargeCardBean)pageList.getList().get(i) ; 
				result.append(i%2==0?"<tr class=\"odd\" ":"<tr ").append("id=").append(rechargeCardBean.getRechargeCode()).append(">");
	                result.append("<td>").append(rechargeCardBean.getRechargeCode()).append("</td>");
					result.append("<td>").append(new Date(rechargeCardBean.getBirthTime())).append("</td>");
					result.append("<td>").append(new Date(rechargeCardBean.getValidTime())).append("</td>");
					//result.append("<td>").append(account.getPoint()).append("</td>");
					result.append("<td>").append(rechargeCardBean.getPoint()).append("</td>");
	                result.append("<td class=\"action\"><a href=\"#\" class=\"delete\" onclick=\"recycleRechargeCard('")
	                .append(rechargeCardBean.getRechargeCode()).append("');return false;\">删除</a></td>");
	            result.append("</tr>");
			}
        result.append("</table>");

		response.getWriter().write(result.toString()) ;

		return Status.OK;		
	}
	private Status getQueryRechargeCardDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		StringBuffer result = new StringBuffer(2048) ;
        result.append("<form action=\"user?actionType=queryRechargeCard\" class=\"jNice\">");
        		result.append("<h3>查询条件</h3>");
        		result.append("<fieldset>");
                        	result.append("<p><label>充值卡:</label><input id=rechargeCard type=\"text\" class=\"text-medium\" maxlength=48/></p>");
							result.append("<p><label>有效期范围 ( 例如2012-12-01 至 2012-12-31 ) :</label>");
                            result.append("<select id=min_validDate_year>");
                    		result.append("<option value=\"\" selected=selected>年</option><option value=2012>2012</option><option value=2013>2013</option><option value=2014>2014</option><option value=2015>2015</option><option value=2016>2016</option><option value=2018>2018</option><option value=2020>2020</option><option value=2100>2100</option>");
                    		result.append("</select>");
                            result.append("<select id=min_validDate_month>");
                    		result.append("<option value=\"\">月</option><option>01</option><option>02</option><option>03</option><option>04</option><option>05</option><option>06</option><option>07</option><option>08</option><option>09</option><option>10</option><option>11</option><option>12</option>");
                    		result.append("</select>");
                            result.append("<select id=min_validDate_day>");
                    		result.append("<option value=\"\">日</option><option>01</option><option>02</option><option>03</option><option>04</option><option>05</option><option>06</option><option>07</option><option>08</option><option>09</option><option>10</option>");
                    		result.append("<option>11</option><option>12</option><option>13</option><option>14</option><option>15</option><option>16</option><option>17</option><option>18</option><option>19</option><option>20</option>");
                    		result.append("<option>21</option><option>22</option><option>23</option><option>24</option><option>25</option><option>26</option><option>27</option><option>28</option><option>29</option><option>30</option><option>31</option>");
                    		result.append("</select>   至   ");
                            result.append("<select id=max_validDate_year>");
                    		result.append("<option value=\"\">年</option><option>2012</option><option>2013</option><option>2014</option><option>2015</option><option>2016</option><option>2018</option><option>2020</option><option>2100</option>");
                    		result.append("</select>");
                            result.append("<select id=max_validDate_month>");
                    		result.append("<option value=\"\">月</option><option>01</option><option>02</option><option>03</option><option>04</option><option>05</option><option>06</option><option>07</option><option>08</option><option>09</option><option>10</option><option>11</option><option>12</option>");
                    		result.append("</select>");
                            result.append("<select id=max_validDate_day>");
                    		result.append("<option value=\"\">日</option><option>01</option><option>02</option><option>03</option><option>04</option><option>05</option><option>06</option><option>07</option><option>08</option><option>09</option><option>10</option>");
                    		result.append("<option>11</option><option>12</option><option>13</option><option>14</option><option>15</option><option>16</option><option>17</option><option>18</option><option>19</option><option>20</option>");
                    		result.append("<option>21</option><option>22</option><option>23</option><option>24</option><option>25</option><option>26</option><option>27</option><option>28</option><option>29</option><option>30</option><option>31</option>");
                    		result.append("</select>");
                    		result.append("</p>");
                            result.append("<p><label>点数范围:</label><input id=min_point type=\"number\" class=\"text-small\" maxlength=8/><input id=max_point type=\"number\" class=\"text-small\" maxlength=8/>");
                            result.append("</p>") ;
                    		result.append("<input type=\"submit\" class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\"  value=\"提交查询\" onclick=\"onQueryRechargeCard();return false;\"/>");
               result.append("</fieldset>");
        result.append("</form>") ;
	    
		response.getWriter().write(result.toString()) ;

		return Status.OK;
	}
	private Status getCreateRechargeCardDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		StringBuffer result = new StringBuffer(2048) ;
        result.append("<form action=\"user?actionType=createRechargeCard\" class=\"jNice\">");
        		result.append("<h3>充值卡创建</h3>");
        		result.append("<fieldset>");
                        	result.append("<p><label>开发者用户名:</label><input id=userName type=\"text\" class=\"text-long\" maxlength=20/></p>");
                        	result.append("<p><label>开发者密码:</label><input id=password type=\"password\" class=\"text-long\" maxlength=20/></p>");
							result.append("<p><label>有效期:</label>");
                            result.append("<select id=validDate_year value=\"\">");
                    		result.append("<option value=\"\">年</option><option>2012</option><option>2013</option><option>2014</option><option>2015</option><option>2016</option><option>2018</option><option>2020</option><option>2100</option>");
                    		result.append("</select>");
                            result.append("<select id=validDate_month>");
                    		result.append("<option value=\"\">月</option><option>01</option><option>02</option><option>03</option><option>04</option><option>05</option><option>06</option><option>07</option><option>08</option><option>09</option><option>10</option><option>11</option><option>12</option>");
                    		result.append("</select>");
                            result.append("<select id=validDate_day>");
                    		result.append("<option value=\"\">日</option><option>01</option><option>02</option><option>03</option><option>04</option><option>05</option><option>06</option><option>07</option><option>08</option><option>09</option><option>10</option>");
                    		result.append("<option>11</option><option>12</option><option>13</option><option>14</option><option>15</option><option>16</option><option>17</option><option>18</option><option>19</option><option>20</option>");
                    		result.append("<option>21</option><option>22</option><option>23</option><option>24</option><option>25</option><option>26</option><option>27</option><option>28</option><option>29</option><option>30</option><option>31</option>");
                    		result.append("</select>");
                    		result.append("</p>");
							//("<input id=validDate_year type=\"text\" class=\"text-small\" maxlength=4/><input id=validDate_month type=\"text\" class=\"text-small\" maxlength=2/><input id=validDate_day type=\"text\" class=\"text-small\" maxlength=2/></p>");
                            result.append("<p><label>初始点数(1元=1000点):</label>");
                            result.append("<input id=point type=text class=text-small maxlength=8></input></p>") ;
                        	result.append("<p><label>个数:</label>");
                        	result.append("<input id=batchSize type=text class=text-small maxlength=4 ></input></p>") ;
                    		result.append("</p>");
                    		result.append("<input type=\"submit\" class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\"  value=\"创建充值卡\" onclick=\"onCreateRechargeCard();return false;\"/>");
               result.append("</fieldset>");
        result.append("</form>") ;
	    
		response.getWriter().write(result.toString()) ;

		return Status.OK;
	}
	private Status querySingleAccount(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		String account = request.getParameter(ServletConstants.arg_account) ;
		if (account == null)
			return Status.INVALID_ARGUMENT ;
		AccountBean accountBean = Globals.getAccountBuffer().get(account) ;
		if (accountBean  == null || accountBean.isDeleted())
			return Status.INVALID_VALUE ;
		
		response.getWriter().write(accountBean.toString()) ;

		return Status.OK;
	}
	/**
	 * 修改子账号的可用点数、有效期
	 * 
	 * */
	private Status updateSingleAccount(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		String account = request.getParameter(ServletConstants.arg_account1) ;
		String strPoint = request.getParameter(ServletConstants.arg_point) ;
		String strValidDate = request.getParameter(ServletConstants.arg_valid_date) ;
		if (account == null || strPoint == null || strValidDate == null)
			return Status.INVALID_ARGUMENT ;
		UserBean user = (UserBean)request.getSession().getAttribute(ServletConstants.s_attr_user) ;
		int point = Integer.parseInt(strPoint) ;
		long validDate = java.sql.Timestamp.valueOf(strValidDate).getTime() ;
		
		Status status = mserver.p2s_updateAccount(user,account,point,validDate);
		if (status == Status.OK)
			response.getWriter().write(status.toString()) ;
		return status;
	}
	private Status getUpdateSingleAccountDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		String account = request.getParameter(ServletConstants.arg_account) ;
		if (account == null)
			return Status.INVALID_ARGUMENT ;
		AccountBean accountBean = Globals.getAccountBuffer().get(account) ;
		if (accountBean == null)
			return Status.INVALID_VALUE ;
		
		StringBuffer result = new StringBuffer(1024) ;

		result.append("<form>");
	     result.append("<fieldset>");
          	result.append("<p><label>子账号:</label>");
          	result.append("<input id=account1 disabled=disabled class=\"text ui-widget-content ui-corner-all textLong\"  type=text maxlength=40 value=\"").append(accountBean.getAccount()).append("\" /></p>");
            result.append("<p><label>总点数:</label><input disabled=disabled class=\"text ui-widget-content ui-corner-all\"  type=\"text\" maxlength=3 value=").append(accountBean.getPoint()).append(" /></p>");
            result.append("<p><label>剩余点数:</label><input disabled=disabled class=\"text ui-widget-content ui-corner-all\"  type=\"text\" maxlength=5 value=").append(accountBean.getLeftPoint()).append(" /></p>");
            result.append("<p><label>有效期:</label><input id=validDate class=\"textLong text ui-widget-content ui-corner-all\" id=difficulty name=difficulty type=\"text\" maxlength=40 value=\"").append(UtilDateTime.toTime(accountBean.getValidTime())).append("\" /></p>");
            result.append("<p><label>增加点数:</label><input id=point class=\"text ui-widget-content ui-corner-all\" id=pointWorker name=pointWorker type=\"text\" maxlength=5 value=0 /></p>");
            result.append("<input type=\"button\"  class=\"x-hidden ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\" value=\"更新\" onclick=\"updateAccount(); return false;\"/>");
          result.append("</fieldset>");
       result.append("</form>");

		response.getWriter().write(result.toString()) ;
		return Status.OK;		
	}
	private Status queryAccount(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		String account = request.getParameter(ServletConstants.arg_account) ;
		String strMinValidDate = request.getParameter(ServletConstants.arg_min_valid_date);
		String strMaxValidDate = request.getParameter(ServletConstants.arg_max_valid_date);
		String strMinLeftPoint = request.getParameter(ServletConstants.arg_min_left_point) ;
		String strMaxLeftPoint = request.getParameter(ServletConstants.arg_max_left_point) ;
		String strPageNo = request.getParameter(ServletConstants.arg_page_no) ;
		
		if (account != null && account.length() > 0 && !AccountBean.isValidFormat(account))
			return Status.INVALID_VALUE ;
		
		long minValidTime = 0 ;
		long maxValidTime = 0 ;
		int minLeftPoint = 0 ;
		int maxLeftPoint = 0 ;
		int pageNo = 1 ;
		try
		{
			if (strMinValidDate != null && strMinValidDate.length() == 10)
				minValidTime = java.sql.Timestamp.valueOf(strMinValidDate+" 00:00:00").getTime() ;
			if (strMaxValidDate != null && strMaxValidDate.length() == 10)
				maxValidTime = java.sql.Timestamp.valueOf(strMaxValidDate+" 23:59:59").getTime() ;
			if (strMinLeftPoint != null && strMinLeftPoint.length() > 0)
				minLeftPoint = Integer.parseInt(strMinLeftPoint) ;
			if (strMaxLeftPoint != null && strMaxLeftPoint.length() > 0)
				maxLeftPoint = Integer.parseInt(strMaxLeftPoint) ;
			if (strPageNo != null && strPageNo.length() > 0)
				pageNo = Integer.parseInt(strPageNo) ;
		}
		catch(Exception e)
		{
			return Status.INVALID_VALUE ;
		}
		
		UserBean user = (UserBean) request.getSession().getAttribute(ServletConstants.s_attr_user) ;
		if (user == null)
			return Status.INVALID_ARGUMENT ;
		PageList pageList = Globals.getAccountList(user.getUserId(), pageNo,null,account, minValidTime, maxValidTime, minLeftPoint, maxLeftPoint);
		if (pageList.getList() == null)
			return Status.OTHER_ERROR ;
		
		StringBuffer result = new StringBuffer(2048) ;
		result.append("<h3>子账号列表</h3>");
        result.append(pageList.getPageInfo().getHtmlByAction("onQueryAccount(this);"));
    	result.append("<table cellpadding=\"0\" cellspacing=\"0\">");
			result.append("<tr>");
				result.append("<td>注册码</td>");
				result.append("<td>生成日期/有效期</td>");
				//result.append("<td>有效期</td>");
				result.append("<td>余额</td>");
				result.append("<td class=\"action\">操作</td>");
			result.append("</tr>");
			AccountBean accountBean ;
			for(int i = 0 ; i < pageList.getList().size() ; i ++)
			{
				accountBean = (AccountBean)pageList.getList().get(i) ; 
				result.append(i%2==0?"<tr class=\"odd\" ":"<tr ").append("id=").append(accountBean.getAccount()).append(">");
	                result.append("<td>").append(accountBean.getAccount()).append("</td>");
					
	                result.append("<td>").append(new Date(accountBean.getBirthTime())).append("/");
	                if (accountBean.isUsed())
						result.append(new Date(accountBean.getValidTime())).append("</td>");
	                else
	                	result.append(accountBean.getValidDate()).append("</td>");
					result.append("<td>").append(accountBean.getLeftPoint()).append("</td>");
					if (!accountBean.isDeleted())
					{
						result.append("<td class=\"action\">");
						result.append("<a href=\"#\" class=\"view\" onclick=\"querySingleAccount('"+accountBean.getAccount()+"'); return false;\">详细</a>");
						result.append("<a href=\"#\" class=\"view\" onclick=\"onUpdateAccount('"+accountBean.getAccount()+"'); return false;\">更新</a>");						
						if (accountBean.isFreeze())
							result.append("<a href=\"#\" class=\"edit\" onclick=\"unfreezeAccount('"+accountBean.getAccount()+"'); return false;\">解冻</a>");
						else
							result.append("<a href=\"#\" class=\"edit\" onclick=\"freezeAccount('"+accountBean.getAccount()+"'); return false;\">冻结</a>");
						result.append("<a href=\"#\" class=\"delete\" onclick=\"recycleAccount('"+accountBean.getAccount()+"');return false;\">删除</a>");
						result.append("</td>");
					}
					else
					{
						result.append("<td class=\"action\">已删除</td>") ;
					}
	            result.append("</tr>");
			}
        result.append("</table>");
	    
		response.getWriter().write(result.toString()) ;

		return Status.OK;		
		
	}
	private Status getQueryAccountDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		StringBuffer result = new StringBuffer(2048) ;
        result.append("<form id=\"queryAccountForm\" action=\"user?actionType=queryAccount\" class=\"jNice\">");
        		result.append("<h3>查询条件</h3>");
        		result.append("<fieldset>");
                        	result.append("<p><label>子账号:</label><input id=account type=\"text\" class=\"text-long\" maxlength=48/></p>");
							result.append("<p><label>有效期范围 ( 例如2012-12-01 至 2012-12-31 ) :</label>");
                            result.append("<select id=min_validDate_year>");
                    		result.append("<option value=\"\" selected=selected>年</option><option value=2012>2012</option><option value=2013>2013</option><option value=2014>2014</option><option value=2015>2015</option><option value=2016>2016</option><option value=2018>2018</option><option value=2020>2020</option><option value=2100>2100</option>");
                    		result.append("</select>");
                            result.append("<select id=min_validDate_month>");
                    		result.append("<option value=\"\">月</option><option>01</option><option>02</option><option>03</option><option>04</option><option>05</option><option>06</option><option>07</option><option>08</option><option>09</option><option>10</option><option>11</option><option>12</option>");
                    		result.append("</select>");
                            result.append("<select id=min_validDate_day>");
                    		result.append("<option value=\"\">日</option><option>01</option><option>02</option><option>03</option><option>04</option><option>05</option><option>06</option><option>07</option><option>08</option><option>09</option><option>10</option>");
                    		result.append("<option>11</option><option>12</option><option>13</option><option>14</option><option>15</option><option>16</option><option>17</option><option>18</option><option>19</option><option>20</option>");
                    		result.append("<option>21</option><option>22</option><option>23</option><option>24</option><option>25</option><option>26</option><option>27</option><option>28</option><option>29</option><option>30</option><option>31</option>");
                    		result.append("</select>   至   ");
                            result.append("<select id=max_validDate_year>");
                    		result.append("<option value=\"\">年</option><option>2012</option><option>2013</option><option>2014</option><option>2015</option><option>2016</option><option>2018</option><option>2020</option><option>2100</option>");
                    		result.append("</select>");
                            result.append("<select id=max_validDate_month>");
                    		result.append("<option value=\"\">月</option><option>01</option><option>02</option><option>03</option><option>04</option><option>05</option><option>06</option><option>07</option><option>08</option><option>09</option><option>10</option><option>11</option><option>12</option>");
                    		result.append("</select>");
                            result.append("<select id=max_validDate_day>");
                    		result.append("<option value=\"\">日</option><option>01</option><option>02</option><option>03</option><option>04</option><option>05</option><option>06</option><option>07</option><option>08</option><option>09</option><option>10</option>");
                    		result.append("<option>11</option><option>12</option><option>13</option><option>14</option><option>15</option><option>16</option><option>17</option><option>18</option><option>19</option><option>20</option>");
                    		result.append("<option>21</option><option>22</option><option>23</option><option>24</option><option>25</option><option>26</option><option>27</option><option>28</option><option>29</option><option>30</option><option>31</option>");
                    		result.append("</select>");
                    		result.append("</p>");
                            result.append("<p><label>余额范围:</label><input id=min_left_point type=\"number\" class=\"text-small\" maxlength=8/><input id=max_left_point type=\"number\" class=\"text-small\" maxlength=8/>");
                            result.append("</p>") ;
                    		result.append("<input type=\"submit\" class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\"  value=\"提交查询\" onclick=\"onQueryAccount();return false;\"/>");
               result.append("</fieldset>");
        result.append("</form>") ;
	    
		response.getWriter().write(result.toString()) ;

		return Status.OK;
	}

	private Status logout(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Status status = Status.OK ;
		
		request.getSession().removeAttribute(ServletConstants.s_attr_user) ;
		response.sendRedirect("index.html");
		return  status;
	}

	private Status getAccountList(HttpServletRequest request,
			HttpServletResponse response) throws IOException
	{
		
		String strPageNo = request.getParameter(ServletConstants.arg_page_no)  ;
		UserBean user = (UserBean) request.getSession().getAttribute(ServletConstants.s_attr_user) ;
		// for debug
		user = Globals.getUserBuffer().getById(1L) ;
		
		if (user == null)
			return Status.INVALID_ARGUMENT ;
		
		int pageNo = 1 ;
		if (strPageNo != null && strPageNo.length() > 0)
			pageNo = Integer.parseInt(strPageNo);
		PageList pageList = Globals.getAccountList(user.getUserId(), pageNo) ;
		
		StringBuffer result = new StringBuffer(2048) ;
		result.append("<h3>子账号列表</h3>");
    	result.append("<table cellpadding=\"0\" cellspacing=\"0\">");
			result.append("<tr>");
				result.append("<td>注册码</td>");
				result.append("<td>生成日期</td>");
				result.append("<td>有效期</td>");
				//result.append("<td>原始点数</td>");
				result.append("<td>余额</td>");
				result.append("<td class=\"action\">操作</td>");
			result.append("</tr>");
			AccountBean account ;
			for(int i = 0 ; i < pageList.getList().size() ; i ++)
			{
				account = (AccountBean)pageList.getList().get(i) ; 
				result.append(i%2==0?"<tr class=\"odd\">":"<tr>");
	                result.append("<td>").append(account.getAccount().toUpperCase()).append("</td>");
					result.append("<td>").append(new Date(account.getBirthTime())).append("</td>");
					result.append("<td>").append(new Date(account.getValidTime())).append("</td>");
					//result.append("<td>").append(account.getPoint()).append("</td>");
					result.append("<td>").append(account.getLeftPoint()).append("</td>");
	                result.append("<td class=\"action\"><a href=\"#\" class=\"edit\">Edit</a><a href=\"#\" class=\"delete\">Delete</a></td>");
	            result.append("</tr>");
			}
        result.append("</table>");
	    
		response.getWriter().write(result.toString()) ;

		return Status.OK;
	}
	
	private Status getCreateAccountDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		UserBean user = (UserBean)request.getSession().getAttribute(ServletConstants.s_attr_user);
		StringBuffer result = new StringBuffer(2048) ;
        result.append("<form class=\"jNice\">");
        		result.append("<h3>子账号创建</h3>");
        		result.append("<fieldset>");
                        	result.append("<p><label>开发者用户名:</label><input id=userName type=\"text\" class=\"text-long\" maxlength=20 value=\"").append(user.getUserName()).append("\" /></p>");
                        	result.append("<p><label>开发者密码:</label><input id=password type=\"password\" class=\"text-long\" maxlength=20 value=\"").append(user.getPassword()).append("\" /></p>");
							result.append("<p><label>有效期(设置日期或者天数,如2013-12-31或者第一次使用后365天到期):</label>");
                            result.append("<select id=validDate_year value=\"\">");
                    		result.append("<option value=\"\">年</option><option>2013</option><option>2014</option><option>2015</option><option>2016</option><option>2018</option><option>2020</option><option>2100</option>");
                    		result.append("</select>");
                            result.append("<select id=validDate_month>");
                    		result.append("<option value=\"\">月</option><option>01</option><option>02</option><option>03</option><option>04</option><option>05</option><option>06</option><option>07</option><option>08</option><option>09</option><option>10</option><option>11</option><option>12</option>");
                    		result.append("</select>");
                            result.append("<select id=validDate_day>");
                    		result.append("<option value=\"\">日</option><option>01</option><option>02</option><option>03</option><option>04</option><option>05</option><option>06</option><option>07</option><option>08</option><option>09</option><option>10</option>");
                    		result.append("<option>11</option><option>12</option><option>13</option><option>14</option><option>15</option><option>16</option><option>17</option><option>18</option><option>19</option><option>20</option>");
                    		result.append("<option>21</option><option>22</option><option>23</option><option>24</option><option>25</option><option>26</option><option>27</option><option>28</option><option>29</option><option>30</option><option>31</option>");
                    		result.append("</select>");
                    		result.append("&nbsp;&nbsp;或&nbsp;&nbsp;<input id=validDays type=text class=textSmall maxlength=5 ></input>天") ;
                    		result.append("</p>");
                            result.append("<p><label>初始点数(1元=1000点,最少100点,最多").append(user.getLeftPoint()).append("点):</label>");
                            result.append("<input id=point type=text class=text-medium maxlength=10></input></p>") ;
                        	result.append("<p><label>个数(最少1个,最大100个):</label>");
                        	result.append("<input id=batchSize type=text class=text-small maxlength=4 ></input></p>") ;
                    		result.append("</p>");
                    		result.append("<input type=\"submit\" class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\"  value=\"创建子账号\" onclick=\"onCreateAccount();return false;\"/>");
               result.append("</fieldset>");
        result.append("</form>") ;
	    
		response.getWriter().write(result.toString()) ;

		return Status.OK;
	}
	
	private Status getReturnPointDlg(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		StringBuffer result = new StringBuffer(2048) ;
		UserBean user = (UserBean)request.getSession().getAttribute(ServletConstants.s_attr_user);
		result.append("<form class=jNice>");
        		result.append("<h3>返点兑换(此操作将返点转换成可用点数，如果需要兑换现金请联系管理员)</h3>");
        		result.append("<fieldset>");
        		result.append("<p><label>可用返点数：").append((int)user.getReturnPoint()).append("</label>");
        		result.append("<label>需要转换点数：</lable>");
        		result.append("<input id=returnPoint type=number class=textSmall maxlength=8 value=\"").append((int)user.getReturnPoint()).append("\" /></p>");
        		result.append("<input type=button class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\" value=转换 onclick=\"onReturnPoint2Point();return false;\"/>");
               result.append("</fieldset>");
        result.append("</form>") ;

		response.getWriter().write(result.toString()) ;
		
		return Status.OK ;
	}
	private Status returnPoint2Point(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		String strReturnPoint = request.getParameter(ServletConstants.arg_return_point) ;
		UserBean user = (UserBean)request.getSession().getAttribute(ServletConstants.s_attr_user) ;
		if (strReturnPoint == null || user == null)
			return Status.INVALID_ARGUMENT ;
		StringBuffer result = new StringBuffer(8) ;
		int point = Integer.parseInt(strReturnPoint) ;
		Status status = mserver.s_returnPoint2Point(user.getUserId(), point, result) ;
		if (status == Status.OK)
			response.getWriter().write(result.toString()) ;
		return status ;
	}
	
	private Status getUserSideBar(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		StringBuffer result = new StringBuffer(1024) ;
		result.append("[") ;
        result.append("{\"id\":\"createAccount\",\"title\":\"子账号创建\",\"url\":\"user?actionType=getCreateAccountDlg\"},") ;
        result.append("{\"id\":\"queryAccount\",\"title\":\"子账号查询\",\"url\":\"user?actionType=getQueryAccountDlg\"},") ;
        result.append("{\"id\":\"rechargeAccount\",\"title\":\"子账号充值\",\"url\":\"user?actionType=getMergeAccountDlg\"},") ;
//        result.append("{\"id\":\"rechargeAccount\",\"title\":\"子账号充值\",\"url\":\"user?actionType=getRechargeAccountDlg\"},") ;
//        result.append("{\"id\":\"createRechargeCard\",\"title\":\"充值卡创建\",\"url\":\"user?actionType=getCreateRechargeCardDlg\"},") ;
//        result.append("{\"id\":\"queryRechargeCard\",\"title\":\"充值卡查询\",\"url\":\"user?actionType=getQueryRechargeCardDlg\"},") ;
        result.append("{\"id\":\"userRecharge\",\"title\":\"我要充值\",\"url\":\"user?actionType=getRechargeUserDlg\"},") ;
        result.append("{\"id\":\"userRecharge\",\"title\":\"返点兑换\",\"url\":\"user?actionType=getReturnPointDlg\"},") ;
        result.append("{\"id\":\"userRecharge\",\"title\":\"开发者信息\",\"url\":\"user?actionType=getUpdateUserDlg\"},") ;
        result.append("{\"id\":\"userRecharge\",\"title\":\"充值记录查询\",\"url\":\"user?actionType=getLoggerDlg\"},") ;
        result.append("{\"id\":\"queryAnswerRecord\",\"title\":\"答题记录查询\",\"url\":\"user?actionType=getQueryAnswerRecordDlg\"},") ;
        result.append("{\"id\":\"queryReturnRecord\",\"title\":\"返点记录查询\",\"url\":\"user?actionType=getQueryReturnRecordDlg\"}") ;
        result.append("]") ;
	    
		response.getWriter().write(result.toString()) ;

		return Status.OK;
	}

	private Status createRechargeCard(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		Status status = Status.OK ;
		String userName = request.getParameter(ServletConstants.arg_user_name) ;
		String password = request.getParameter(ServletConstants.arg_password) ;	
		String strPoint = request.getParameter(ServletConstants.arg_point);
		String strValidDate = request.getParameter(ServletConstants.arg_valid_date);
		String strBatchSize = request.getParameter(ServletConstants.arg_batch_size) ;
		if (strPoint == null || userName == null || password == null || strValidDate ==  null)
			return Status.INVALID_ARGUMENT;
		int point = Integer.parseInt(strPoint);
		long validTime = 0 ;
		try
		{
			validTime = java.sql.Timestamp.valueOf(strValidDate+" 23:59:59").getTime() ;
		}
		catch(Exception e)
		{
			return Status.INVALID_VALUE ;
		}
		int batchSize = Integer.parseInt(strBatchSize) ;
		StringBuffer result = new StringBuffer(48);
		status = mserver.p2s_batchGenerateRenewCard(userName, password, validTime, batchSize, point, result) ;
		if (status == Status.OK)
		{// 返回充值卡号
			response.getWriter().write(result.toString()) ;
		}
		return status ;
	}

	private Status rechargeUser(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		Status status = Status.OK ;
		String userName = request.getParameter(ServletConstants.arg_user_name) ;
		String rechargeCard = request.getParameter(ServletConstants.arg_recharge_card);
		if (rechargeCard == null || userName == null)
			return Status.INVALID_ARGUMENT;
		
		StringBuffer result = new StringBuffer(10);
		status = mserver.p2s_rechargeUser(userName,rechargeCard,result);
		if (status == Status.OK)
		{// 返回充值点数
			response.getWriter().write(result.toString()) ;
		}
		return status ;
	}

	private Status createUser(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		Status status = Status.OK ;
		String userName = request.getParameter(ServletConstants.arg_user_name);
		String password  = request.getParameter(ServletConstants.arg_password);
		String qq = request.getParameter(ServletConstants.arg_qq) ;
		String email = request.getParameter(ServletConstants.arg_email) ;
		String zhifubao = request.getParameter(ServletConstants.arg_zhifubao) ;
		String phone = request.getParameter(ServletConstants.arg_phone) ;
		String validCodeAnswer = request.getParameter(ServletConstants.arg_valid_code_answer) ;;
		String validCode = (String)request.getSession().getAttribute(ServletConstants.s_attr_validate_code) ;
		if (validCode == null || !validCodeAnswer.equalsIgnoreCase(validCode))
			return Status.INVALID_VALIDATE_CODE ;
		status =  mserver.s_regUser(userName, password, qq, email,zhifubao,phone,0) ;
		if (status == Status.OK)
		{
			request.getSession().removeAttribute(ServletConstants.s_attr_validate_code) ;
			response.getWriter().write(Status.OK.toString()) ;
		}
		return status ;
	}
	private Status createAccount(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		Status status = Status.OK ;
//		UserBean user = (UserBean)request.getSession().getAttribute(ServletConstants.s_attr_user);
		String userName = request.getParameter(ServletConstants.arg_user_name) ;
		String password = request.getParameter(ServletConstants.arg_password) ;
		String strPoint = request.getParameter(ServletConstants.arg_point);
		String strValidDate = request.getParameter(ServletConstants.arg_valid_date);
		String strBatchSize = request.getParameter(ServletConstants.arg_batch_size) ;
		if (strPoint == null || userName == null ||
				strValidDate == null || password == null || strBatchSize == null)
			return Status.INVALID_ARGUMENT;

		int point = Integer.parseInt(strPoint);
		long validTime = 0 ;
		// 如果包含-,表示日期形式
		if (strValidDate.indexOf('-') >= 0 )
		{
			if (strValidDate.indexOf(':') > 0)// yyyy-mm-dd hh:mm:ss
				validTime = java.sql.Timestamp.valueOf(strValidDate).getTime();
			else
			{// yyyy-mm-dd
				validTime = java.sql.Timestamp.valueOf(strValidDate+" 23:59:59").getTime() ;
			}
			if (validTime < System.currentTimeMillis())
				return Status.INVALID_VALUE ;
		}
		else// 只是一个数字，表示天数形式
		{
			validTime = Long.parseLong(strValidDate) ;
			if (validTime < Constants.min_day_validity ||
					validTime > Constants.max_day_validity)
				return Status.INVALID_VALUE ;
			// 天数 转换为 毫秒数
			validTime = validTime*Constants.millseconds_per_day;
		}
		int batchSize = Integer.parseInt(strBatchSize) ;
		StringBuffer result = new StringBuffer(48);
		status = mserver.p2s_batchGenerateAccount(userName, password, validTime, batchSize, point, result) ;
		
		if (status == Status.OK)
		{
			response.getWriter().write(result.toString()) ;
		}
		return status ;
	}	

	// 注册用户页面
	private Status regUser(HttpServletRequest request,
			HttpServletResponse response) 
	{
        try 
        {
            RequestDispatcher disp = request.getRequestDispatcher("modules/user/regUser.html") ;
			disp.forward(request, response) ;
		}
        catch (Exception e) 
        {
			e.printStackTrace();
			return Status.OTHER_ERROR ;
		}
		return Status.OK;
	}

	// 登陆
	private Status login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		Status status = Status.OK ;
		String userName = request.getParameter(ServletConstants.arg_user_name) ;
		String password = request.getParameter(ServletConstants.arg_password) ;
		String validCodeAnswer = request.getParameter(ServletConstants.arg_valid_code_answer) ;
		String validCode = (String)request.getSession().getAttribute(ServletConstants.s_attr_validate_code) ;
		String qq = request.getParameter(ServletConstants.arg_qq) ;
		String email = request.getParameter(ServletConstants.arg_email) ;
		if(validCodeAnswer == null || validCode == null)
			return Status.INVALID_ARGUMENT ;
		if(!validCodeAnswer.equalsIgnoreCase(validCode))
			return Status.INVALID_VALIDATE_CODE;
		if (userName == null || password == null)
		{
			status = Status.INVALID_ARGUMENT ;
		} 
		else
		{
			status = mserver.s_login(userName,password) ;
			if (status == Status.OK)
			{
				UserBean user = mserver.p2s_getUser(userName) ;
				System.out.println(user) ;
				request.getSession().setAttribute(ServletConstants.s_attr_user, user) ;
				response.getWriter().write(Status.OK.statusCode.toString()) ;
			}
		}
		return  status;
	}

	/**
	 * 回收子账号
	 * 
	 * */
	private Status recycleAccount(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		String userName = null ;
		String password = null ;
		UserBean user = (UserBean)request.getSession().getAttribute(ServletConstants.s_attr_user) ;
		
		userName = user.getUserName() ;
		password = user.getPassword() ;
		
		String account = request.getParameter(ServletConstants.arg_account) ;
		Status status = mserver.p2s_recycleAccount(userName, password, account);
		if (status == Status.OK)
		{
			response.getWriter().write(status.statusCode.toString()) ;
		}
		return status;
	}	
	/**
	 * 回收充值卡
	 * 
	 * */
	private Status recycleRechargeCard(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		String userName = null ;
		String password = null ;
		UserBean user = (UserBean)request.getSession().getAttribute(ServletConstants.s_attr_user) ;

		userName = user.getUserName() ;
		password = user.getPassword() ;
		
		String rechargeCard = request.getParameter(ServletConstants.arg_recharge_card) ;
		Status status = mserver.p2s_recycleRechargeCard(userName, password, rechargeCard);
		if (status == Status.OK)
		{
			response.getWriter().write(status.statusCode.toString()) ;
		}
		return status;
	}
}
